package com.qf.service.impl;

import com.qf.mapper.DeviceMapper;
import com.qf.mapper.DeviceTypeMapper;
import com.qf.mapper.FarmMapper;
import com.qf.model.Device;
import com.qf.model.DeviceType;
import com.qf.model.Farm;
import com.qf.page.PageResult;
import com.qf.page.QueryPageBean;
import com.qf.service.DeviceService;
import com.qf.service.DeviceTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceTypeMapper deviceTypeMapper;
    @Autowired
    private FarmMapper farmMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public int add(Device device) {
        device.setUpdateTime(new Date());
        //将阈值存入redis
        stringRedisTemplate.opsForValue().set("thresholdMax"+device.getId(),Float.toString(device.getThresholdMax()));
        stringRedisTemplate.opsForValue().set("thresholdMin"+device.getId(),Float.toString(device.getThresholdMin()));


        return deviceMapper.add(device);
    }

    @Override
    public Device findById(int id) {
        return deviceMapper.findById(id);
    }


    @Override
    @Transactional
    public int edit(Device device) {
        device.setUpdateTime(new Date());
        //将阈值存入redis
        stringRedisTemplate.opsForValue().set("thresholdMax"+device.getId(),Float.toString(device.getThresholdMax()));
        stringRedisTemplate.opsForValue().set("thresholdMin"+device.getId(),Float.toString(device.getThresholdMin()));

        int i = deviceMapper.edit(device);
        return i;
    }


    @Override
    @Transactional
    public int delete(int id) {
        return deviceMapper.delete(id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer CurrentPage = queryPageBean.getCurrentPage();
        Integer PageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageResult pageResult = new PageResult();
        List<Device> rows = deviceMapper.findPage((CurrentPage - 1) * PageSize, PageSize, queryString);
        for (Device row : rows) {
            Farm farm = farmMapper.findById(row.getFarmId());
            row.setFarm(farm);
            DeviceType deviceType = deviceTypeMapper.findById(row.getTypeId());
            row.setDeviceType(deviceType);
        }
        Long total = deviceMapper.count(queryString);
        pageResult.setRows(rows);
        pageResult.setTotal(total);
        return pageResult;
    }
}
